import { Dimensions } from "@sapi-game/constants";
import { GameComponent, StopWatch } from "@sapi-game/gameComponent";
import { Game } from "@sapi-game/main";
import { Duration } from "@sapi-game/utils";
import { DirtShopMainState } from "../states/mainState";

export class DirtShopDaemon extends GameComponent<DirtShopMainState> {
    protected override onAttach(): void {
        this.subscribe(
            Game.events.interval,
            () => {
                this.setSpawnPoint();
                this.checkEnd();
            },
            new Duration(10)
        );
        const stopWatch = this.state.getComponent(StopWatch);
        //时间提醒
        this.subscribe(stopWatch.events.tick, (arg) => {
            if (arg.elapsedTime % 300 == 0) {
                this.context.groupSet.sendMessage(
                    "游戏已开始" + Math.floor(arg.elapsedTime / 60) + "分钟"
                );
            }
        });
    }

    /**没有重生点就改为默认 */
    setSpawnPoint() {
        this.context.host.forEach((p) => {
            if (p.player.getSpawnPoint() == undefined) {
                p.player.setSpawnPoint({
                    dimension: Dimensions.Overworld,
                    ...this.context.map.hostSpawnPoint,
                });
            }
        });
        this.context.attacker.forEach((p) => {
            if (p.player.getSpawnPoint() == undefined) {
                p.player.setSpawnPoint({
                    dimension: Dimensions.Overworld,
                    ...this.context.map.attackerSpawnPoint,
                });
            }
        });
    }

    checkEnd() {
        const liveHostCnt = this.context.host.filter(
            (p) => p.alive && p.isValid
        ).length;
        if (liveHostCnt == 0) {
            this.state.end();
        }
    }
}
